import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { mobileValidate } from '@core/util/formControl-validate-utils';
import { OtcShopService } from '@core/routes-services/otc-shop.service';
import { AgentService } from '@core/routes-services/agent.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { debounceTime, switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
import { OtcCustomerService } from '@core/routes-services/otc-customer.service';
import { OtcShopBrandService } from '@core/routes-services/otc-shop-brand.service';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../constant/config';
import { CacheService } from '@core/routes-services/cache.service';

@Component({
  selector: 'app-otc-shop-edit',
  templateUrl: './otc-shop-edit.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }

    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }

    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `],
})
export class OtcShopEditComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;
  cityOptions: any;

  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};
  componentDirty: boolean = false;

  geocoder: any;
  map: any;
  // 公众号二维码图ticket
  //  访问方式 ： https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
  wxPublicImgDomain = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';


  loadingOption: boolean = false;
  searchChange$ = new BehaviorSubject('');
  cusList: any [] = [];

  allBrand: any [] = [];
  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private otcShopService: OtcShopService,
              private otcCustomerService:OtcCustomerService,
              private otcShopBrandService:OtcShopBrandService,
              private agentService: AgentService,
              private cacheService: CacheService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.initBrand();
    this.getCitiesData();
    this.initQQMap();
    this.initValidateForm();
    const searchFanOptions = (name: string) => this.otcCustomerService.searchCenterSalesManOptions(this.entity.centerId, name).then((res) => {
      if (res.status.toString().startsWith('20')) {
        return res.data.content;
        // this.page = res.data;
        // ++this.page.number;
      } else {
        this.message.warning(res.message);
        return [];
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      return [];
    });
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(searchFanOptions));
    optionList$.subscribe(data => {
      console.log(data)
      this.cusList = data;

      if(this.entity.customerId){
        if(this.cusList.findIndex((r)=>r.id == this.entity.customerId) == -1){
          this.cusList.push({id:this.entity.customerId,name:this.entity.name});
        }
      }
      this.loadingOption = false;
    });
  }

  onSearch(value: string): void {
    this.loadingOption = true;
    this.searchChange$.next(value);
  }

  initBrand(){
    this.isLoading = true;
    this.otcShopBrandService.getAll().then((res) => {
      console.log(res)
      if (res.status.toString().startsWith("20")) {
        this.allBrand = res.data.otcShopBrandList.filter((b)=>b.centerId == this.entity.centerId && b.status == 1);
        console.log(this.allBrand)
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error)
      this.isLoading = false;
    });
  }
  initValidateForm() {
    this.entity.cityArea = this.entity.province ? [this.entity.province, this.entity.city, this.entity.county] : new Array();
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(100)]],
      shopkeeperName: [this.entity.shopkeeperName, [ Validators.maxLength(32)]],
      shopkeeperPhone: [this.entity.shopkeeperPhone, [ mobileValidate]],
      customerId: [this.entity.customerId, [Validators.required]],
      brandId: [this.entity.brandId, [Validators.required]],
      cityArea: [this.entity.cityArea, [Validators.required]],
      address: [this.entity.address, [Validators.required, Validators.maxLength(60)]],
      imgKey: [this.entity.imgKey, []],
    });
  }

  initQQMap() {
    let that = this;
    var center = new qq.maps.LatLng(24.44579, 118.08243);//厦门
    this.map = new qq.maps.Map(document.getElementById('container'), {
      center: center,
      zoom: 15,
    });
    //调用地址解析类
    this.geocoder = new qq.maps.Geocoder({
      complete: function(result) {
        console.log(result);
        that.entity.longitude = result.detail.location.lng;
        that.entity.latitude = result.detail.location.lat;
      },
    });
  }

  codeAddress() {
    var address = this.validateForm.value.cityArea.join(',');
    //通过getLocation();方法获取位置信息值
    this.geocoder.getLocation(address + ',' + this.validateForm.value.address);
  }

  getCitiesData() {
    this.agentService.getCitiesData().then((res) => {
      this.cityOptions = res;
    }, error => {
      console.log(error);
    });
  }

  public onChanges(values: any): void {
    console.log(values, this.validateForm.value);
    if (values.length == 3) {
      this.codeAddress();
    }
  }

  addressChange() {
    console.log(this.validateForm.value);
    this.codeAddress();
  }

  submitForm(): void {
    let that = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      if (!this.validateForm.value.cityArea || this.validateForm.value.cityArea.length == 0) {
        this.message.warning('请选择店铺地址');
        return;
      }
      if (this.validateForm.value.cityArea.length < 3) {
        this.message.warning('店铺地址必须选到区县级');
        return;
      }
      this.codeAddress();
      this.entity.province = this.validateForm.value.cityArea[0];
      this.entity.city = this.validateForm.value.cityArea[1];
      this.entity.county = this.validateForm.value.cityArea[2];
      Object.assign(this.entity, this.validateForm.value);
      that.isLoading = true;
      setTimeout(function() {
        that.otcShopService.saveOrUpdateEntity(that.entity.id, that.entity).then((res) => {
          if (res.status.toString().startsWith('20')) {
            that.modal.close(true);
          } else {
            that.message.warning(res.message);
          }
          that.isLoading = false;
        }, error => {
          that.message.error(error.message ? error.message : error.error);
          that.isLoading = false;
        });
      }, 1100);

    }
  }


  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.imgKey = fileList[findIdx].url;
      this.validateForm.controls.imgKey.setValue(this.entity.imgKey);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }


  close() {
    this.modal.destroy();
  }

}
